<?php
    if (!defined('EXPONENT')) exit('');
    if (exponent_permissions_check(array('administrate','configure'),$loc)){
        if($_REQUEST['reload_var']==1)
        {
            $temp=$db->selectObjects('mailsystem_template');
            $temps=null;
            foreach($temp as $v)
            {
                $temps[$v->id]=$v; 
            }
            echo json_encode($temps);
        }
        else
        {
            //// pagination
            $sql_where = '1';
            $search_name = '';
            $from_date = 0;
            $to_date = 0;
            $mail_status = 0;
            $page=1;
            $sort="";

            if(isset($_REQUEST['search_name'])&&isset($_REQUEST['search_detail']))
            {
                $search_detail = $_REQUEST['search_detail'];  
                $search_name = $_REQUEST['search_name'];  
                $sql_where .= " AND `$search_name` LIKE '%{$search_detail}%'"; 
            }
            if(isset($_REQUEST['group']))
            {            
                $group = $_REQUEST['group']; 
                if($group!='All')  
                    $sql_where .= " AND `group` = '{$group}'"; 
            }

            if (isset($_REQUEST['sortName']))        {
                $sort=$_REQUEST['sortName'];            
                $sortOrder="ASC";
                if (isset($_REQUEST['sortOrder']) && ($_REQUEST['sortOrder'] != "asc"))
                    $sortOrder = "DESC";
                $sort = " ORDER BY `{$sort}` {$sortOrder}";
            }
            else
                $sort = "ORDER BY id DESC";

            if (isset($_REQUEST['page']))
                $page=intval($_REQUEST['page']);
            $pageSize=10;
            if (isset($_REQUEST['pageSize']))
                $pageSize=intval($_REQUEST['pageSize']);
            $start=($page-1)*$pageSize;
            $data=$db->selectObjects('mailsystem_template',"{$sql_where} {$sort} limit {$start},{$pageSize}");

            foreach ($data as $k=>$v)
            {            
                if($v->date!=0)
                    $v->date_formater = date("F j, Y g:i a", $v->date);
                else
                    $v->date_formater='';
            }
            $ret_object = null;
            $ret_object->total = $db->countObjects('mailsystem_template',"{$sql_where} {$sort} limit {$start},{$pageSize}");
            $ret_object->rows = $data;
            echo json_encode($ret_object);
        }
    }
    else
        echo exponent_http_error(403);

?>